import axios from 'axios'
import { ElMessage } from 'element-plus';
import { getToken, getUsername, removeToken, removeUsername } from './cookies';
import router from '@/router';
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API,// 请求地址
  timeout: 5000,// 超时
});
service.interceptors.request.use((config) => {
  getToken() && (config.headers["Token"] = getToken());
  getUsername() && (config.headers["Username"] = getUsername());
  return config
}, (error) => {
  return Promise.reject(error)
});

service.interceptors.response.use((response) => {
  // console.log(response, 'response');
  const data = response.data;
  if (data.resCode === 0) {
    return Promise.resolve(data)
  } else {
    ElMessage({
      message: data.message,
      type: 'error'
    });
    return Promise.reject(data)
  }
}, (error) => {
  console.log(error.request, 'error.request')
  const errorData = JSON.parse(error.request.response);
  if (errorData.resCode === 1010) {
    router.replace({
      name: "Login"
    })
    removeToken()
    removeUsername()
  }
  if (errorData.msg) {
    ElMessage({
      message: errorData.msg,
      type: 'error'
    })
  }
  return Promise.reject(errorData)
});
export default service;